<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;
use App\Repositories\FileRepo;
class FileController extends Controller
{
    private $host = '';
    public function __construct(Request $request)
    {
        $this->host = $request->getScheme().'://'.$request->getHost();
        // var_dump($request->getHost());
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function upload(Request $request)
    {
        $file = $request->file('file');

        if(!$file)  return  $this->errRes();
        $originalName = $file->getClientOriginalName();

        $fileRepo = new FileRepo;

        if($path = $fileRepo->exits($originalName)) {
            // return $this->sucRes(200,['path'=>$path]);
            return ['errno'=>0,'data'=>['url'=>$this->host.$path]];
        }
        $mineType = $file->guessClientExtension();

        $extension = '';
        if($mineType == 'jpeg') {
            $extension = 'jpg';
        } else{
            $extension = $mineType;
        }
      
        $filePath = date('/Y/m/d/',time()).uniqid().'.'.$extension;

        Storage::put($filePath,file_get_contents($file->getRealPath()));

        $path = '/uploads'.$filePath;
      
        if(file_exists('.'.$path)) {
                $fileRepo->rsycSave($path,$originalName);
             // return $this->sucRes(200,['url'=>$this->host.$path]);
                return ['errno'=>0,'data'=>['url'=>$this->host.$path]];
        } else{
             return $this->errRes(-1,'文件保存失败'.$path);
        }
    }
}
